LOOPING STATEMENT

Course- PHP TUTOTRIAL >

PHP - While Loop

Repetitive tasks are always a burden to us. Deleting spam email, sealing 50 envelopes, and going to work are all examples of tasks that are repeated. The nice thing about programming is that you can avoid such repetitive tasks with a little bit of extra thinking. Most often these repetitive tasks are conquered in the loop.

The idea of a loop is to do something over and over again until the task has been completed. Before we show a real example of when you might need one, let's go over the structure of the PHP while loop.

Simple While Loop Example

The function of the while loop is to do a task over and over as long as the specified conditional statement is true. This logical check is the same as the one that appears in a PHP if statement to determine if it is true or false. Here is the basic structure of a PHP while loop:

Pseudo PHP Code:

while ( conditional statement is true){
	//do this code;
}

This isn't valid PHP code, but it displays how the while loop is structured. Here is the break down of how a while loop functions when your script is executing:

  1. The conditional statement is checked. If it is true, then (2) occurs. If it is false, then (4) occurs.
  2. The code within the while loop is executed.
  3. The process starts again at (1). Effectively "looping" back.
  4. If the conditional statement is false, then the code within is not executed and there is no more looping. The code following the while loop is then executed like normal.

A Real While Loop Example

Imagine that you are running an art supply store. You would like to print out the price chart for number of brushes and total cost. You sell brushes at a flat rate, but would like to display how much different quantities would cost. This will save your customers from having to do the mental math themselves.

You know that a while loop would be perfect for this repetitive and boring task. Here is how to go about doing it.

Pseudo PHP Code:

$brush_price = 5; 
$counter = 10;

echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
while ( $counter <= 100 ) {
	echo "<tr><td>";
	echo $counter;
	echo "</td><td>";
	echo $brush_price * $counter;
	echo "</td></tr>";
	$counter = $counter + 10;
}
echo "</table>";

Display:

Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500

Pretty neat, huh? The loop created a new table row and its respective entries for each quantity, until our counter variable grew past the size of 100. When it grew past 100 our conditional statement failed and the loop stopped being used. Let's review what is going on.

  1. We first made a $brush_price and $counter variable and set them equal to our desired values.
  2. The table was set up with the beginning table tag and the table headers.
  3. The while loop conditional statement was checked, and $counter (10) was indeed smaller or equal to 100.
  4. The code inside the while loop was executed, creating a new table row for the price of 10 brushes.
  5. We then added 10 to $counter to bring the value to 20.
  6. The loop started over again at step 3, until $counter grew larger than 100.
  7. After the loop had completed, we ended the table.

You may have noticed that we placed slashes infront the quotations in the first echo statement. You have to place slashes before quotations if you do not want the quotation to act as the end of the echo statement. This is called escaping a character and it is discussed in our PHP Strings lesson.

With proper use of loops you can complete large tasks with great ease.

PHP - For Loop

The for loop is simply a while loop with a bit more code added to it. The common tasks that are covered by a for loop are:

  1. Set a counter variable to some initial value.
  2. Check to see if the conditional statement is true.
  3. Execute the code within the loop.
  4. Increment a counter at the end of each iteration through the loop.

The for loop allows you to define these steps in one easy line of code. It may seem to have a strange form, so pay close attention to the syntax used!

For Loop Example

Let us take the example from the while loop lesson and see how it could be done in a for loop. The basic structure of the for loop is as follows:

Pseudo PHP Code:

for ( initialize a counter; conditional statement; increment a counter){
	do this code;
}

Notice how all the steps of the loop are taken care of in the for loop statement. Each step is separated by a semicolon: initiliaze counter, conditional statement, and the counter increment. A semicolon is needed because these are separate expressions. However, notice that a semicolon is not needed after the "increment counter" expression.

Here is the example of the brush prices done with a for loop .

PHP Code:

$brush_price = 5; 

echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
for ( $counter = 10; $counter <= 100; $counter += 10) {
	echo "<tr><td>";
	echo $counter;
	echo "</td><td>";
	echo $brush_price * $counter;
	echo "</td></tr>";
}
echo "</table>";

Display:

Quantity Price
10 50
20 100
30 150
40 200
50 250
60 300
70 350
80 400
90 450
100 500

It is important to note that both the for loop and while loop implementation of the price chart table are both OK at getting the job done. However, the for loop is somewhat more compact and would be preferable in this situation. In later lessons we will see where the while loop should be used instead of the for loop.

PHP For Each Loop

Imagine that you have an associative array that you want to iterate through. PHP provides an easy way to use every element of an array with the Foreach statement.

In plain english this statement will do the following:

  • For each item in the specified array execute this code.

While a For Loop and While Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.

PHP For Each: Example

We have an associative array that stores the names of people in our company as the keys with the values being their age. We want to know how old everyone is at work so we use a Foreach loop to print out everyone's name and age.

PHP Code:

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $key => $value){
	echo "Name: $key, Age: $value <br />";
}

Display:

Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34

The syntax of the foreach statement is a little strange, so let's talk about it some.

Foreach Syntax: $something as $key => $value

This crazy statement roughly translates into: For each element of the $employeeAges associative array I want to refer to the key as $key and the value as $value.

The operator "=>" represents the relationship between a key and value. You can imagine that the key points => to the value. In our example we named the key $key and the value $value. However, it might be easier to think of it as $name and $age. Below our example does this and notice how the output is identical because we only changed the variable names that refer to the keys and values.

PHP Code:

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $name => $age){
	echo "Name: $name, Age: $age <br />";
}

Display:

Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34

PHP - Do While Loop

A "do while" loop is a slightly modified version of the while loop. If you recal from one of the previous lessons on While Loops the conditional statement is checked comes back true then the code within the while loop is executed. If the conditional statement is false then the code within the loop is not executed.

On the other hand, a do-while loop always executes its block of code at least once. This is because the conditional statement is not checked until after the contained code has been executed.

PHP - While Loop and Do While Loop Contrast

A simple example that illustrates the difference between these two loop types is a conditional statement that is always false. First the while loop:

PHP Code:

$cookies = 0;
while($cookies > 1){
	echo "Mmmmm...I love cookies! *munch munch munch*";
} 

Display:

 

As you can see, this while loop's conditional statement failed (0 is not greater than 1), which means the code within the while loop was not executed. Now, can you guess what will happen with a do-while loop?

PHP Code:

$cookies = 0;
do {
	echo "Mmmmm...I love cookies! *munch munch munch*";
} while ($cookies > 1);

Display:

Mmmmm...I love cookies! *munch munch munch*

The code segment "Mmmm...I love cookies!" was executed even though the conditional statement was false. This is because a do-while loop first do's and secondly checks the while condition!

Chances are you will not need to use a do while loop in most of your PHP programming, but it is good to know it's there!